from fastapi import APIRouter, Header

from DataModels.database import User
from DataModels.share import RespInfo, RespResultCode, StatusInfo
from utils.token import check_token
from utils.user import user_to_user_info

# => response
# {info: UserInfo}

token_router = APIRouter(prefix="/token")


@token_router.get("")
async def get_user_info_by_token(token=Header(None)):
    ok, info = check_token(token)
    if not ok:
        return info
    token = info
    phone = token.phone  # type: ignore
    user = await User.find_one(User.phone == phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="未找到手机号",
            )
        )

    user_info = user_to_user_info(user)

    return RespInfo(
        info=user_info,
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="获取成功",
        ),
    )
